import { FunctionComponent } from 'react';
import { Form, Input, Button, Toast } from 'antd-mobile';
import './index.less';
import Icon from "@/assets/back.jpg"
import { LeftOutline } from 'antd-mobile-icons'
import { history, useSelector, useDispatch } from "umi"
import httpService from '@/core/http.service';
import apiConfig from '@/core/api.config';
import { IDvaModels, IGloablDvaState } from "@/models"

type FormValues = {
    phone: string;
    verificationCode: string;
};

interface IProps { }

const LoginPage: FunctionComponent<IProps> = () => {

    // 获取dva中的变量
    const {count} = useSelector<IDvaModels, IGloablDvaState>(state => state.global)
    const dispatch = useDispatch()
    // 更新dva中的变量
    const add = ()=>{
        dispatch({
            type: "global/setCount",
            payload: count+1
        })
    }
    const [form] = Form.useForm<FormValues>();

    const onFinish = (values: FormValues) => {
        const { phone, verificationCode } = values;
        if (!(/^1[3-9]\d{9}$/.test(phone))) {
            Toast.show({
                content: "手机号输入不正确!"
            })
            return
        }
        if (verificationCode !== '6666') {
            Toast.show({
                content: "验证码输入不正确!"
            })
            return
        }
        httpService.request<any>({
            url: apiConfig.user.login,
            method: "GET",
            data: { phone }
        }).then(userId => {
            localStorage.setItem("userId", userId)
            history.replace({
                pathname: '/'
            })
        })
    };

    return (
        <div className="login-container">
            <LeftOutline fontSize={20} className='back' />
            <div className="login-header">
                <img src={Icon} alt="" />
            </div>
            <Form form={form}
                onFinish={onFinish}
                layout="horizontal"
                className="login-form">

                <Form.Item
                    name="phone"
                    label="手机号"
                >
                    <Input placeholder="请输入手机号" type='number' clearable />
                </Form.Item>

                <Form.Item
                    name="verificationCode"
                    label="验证码"
                >
                    <Input placeholder="请输入验证码6666" type='number' clearable />
                </Form.Item>
            </Form>
            <Button onClick={() => {
                form.submit()
            }} block style={{ backgroundColor: '#23266E', borderColor: '#23266E' }} color='primary' size='large'>登录</Button>
            <div className="terms-text">首次登录后默认注册用户并同意《注册会员服务条款》</div>
        </div>
    );
};

export default LoginPage;